package edu.thu.cs;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

public class StaticFunc {
	public static String[] cv = new String[] {
		"'", "\\\\'",
		"\"", "\\\\\"",
		"\n", "\\n"
	};
	
	public static double getRe(double d1, double d2) {
		return d1 + d2;
	}

	/**
	 * 字符串转义 
	 * @param str 输入以及输出
	 */
	static public String mysqlRealEscapeString(String str) {
		if (str == null) str = "";
		for (int i=0; i<cv.length; i+=2)
			if (str.indexOf(cv[i]) >= 0)
				str = str.replaceAll(cv[i], cv[i+1]);
        return str;
	}

	/**
	 * 字符串反转义 
	 * @param str 输入以及输出
	 */
	static public String mysqlEscapeString(String str) {
		if (str == null) str = "";
		for (int i=0; i<cv.length; i+=2)
			if (str.indexOf(cv[i+1]) >= 0)
				str = str.replaceAll(cv[i+1], cv[i]);
        return str;
	}

	static public String toJson(List<HashMap<String, String>> obj) {
		String x = "[";
		for (int i=0; i<obj.size(); i++) {
			x += toJson(obj.get(i));
			if (i != obj.size()-1)
				x += ",";
		}
		x += ']';
		return x;
	}
	
	static public String toJson(HashMap<String, String> obj) {
		String x = "{";
		int first = 0;
		for(HashMap.Entry<String, String> entry : obj.entrySet()) {
		    String key = entry.getKey();
		    String value = entry.getValue();
		    key = mysqlRealEscapeString(key);
		    value = mysqlRealEscapeString(value);
		    if (first != 0) x += ',';
		    first ++;
		    x += "\"" + key + "\":\"" + value + "\""; 
		}
		x += '}';
		return x;
	}
	
	static public String encodingUtf8(String str) {
		if (str == null) return "";
		try {
			return new String(str.getBytes("ISO-8859-1"));
		} catch (UnsupportedEncodingException e) {
			System.out.println("Encoding Error" + e);
			return "";
		}
	}
}
